package org.zlm.git_study.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.zlm.git_study.annotation.AccessLimit;

import java.io.OutputStream;
import java.lang.invoke.MethodHandle;

/**
 * @author zlm
 * @date 2023/12/22
 */
@Component
public class InterfaceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //是否方法请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //方法上是否有注解
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);
            if(methodAnnotation == null){
                return true;
            }

            boolean needLogin = methodAnnotation.needLogin();
            if(needLogin){
                //判断登陆
                String id = request.getParameter("id");
                if(StringUtils.hasText(id)){
                    return true;
                }else{
                    response.setContentType("application/json;charset=UTF-8");
                    OutputStream out = response.getOutputStream();
                    String str  = "未登录";
                    out.write(str.getBytes("UTF-8"));
                    out.flush();
                    out.close();
                    return false;
                }
            }

        }

        return true;
    }
}
